//
//  NearVC.swift
//  YueChat
//
//  Created by IMac on 2024/10/16.
//

import UIKit

class NearVC: BaseVC,GroupDetailHeadDelegate {

    
    
    var tel = ""
    var userArray = [DMCCUser]()
    var more = DMCCDapp()
    var listApi = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.title = "推荐"
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
            tableView.sectionFooterHeight = 0
        }
        
//        tableView.register(UINib(nibName: "NearHeadCell", bundle: nil), forCellReuseIdentifier: "NearHeadCell")
        tableView.register(NearHeadView.self, forHeaderFooterViewReuseIdentifier: "NearHeadView")
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
        tableView.register(UINib(nibName: "NearMoreCell", bundle: nil), forCellReuseIdentifier: "NearMoreCell")
        
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 1
            tableView.estimatedSectionFooterHeight = 1
            tableView.estimatedSectionHeaderHeight = 1
        }
        
        let login = gosnLogin.loadLoginData()
        
        if let useInfo = login["userInfo"] as? [String:Any]{
            if let mobile = useInfo["mobile"] as? String{
                tel = mobile
            }
        }
        
        if let apiSetConfig = login["apiSetConfig"] as? [String:Any]{
            if let apis = apiSetConfig["apis"] as? NSDictionary{
                if let functionShop = apis["functionShop"] as? String{
                    
                    let json = OsnUtils.toJson(functionShop)
                    more = DMCCDapp.deserialize(from: json)!
                }
                if let functionListApi = apis["functionListApi"] as? String{

                    listApi = functionListApi
                }
                
            }
        }

        getUsers()
        
       
        self.view .insertSubview(self.nullView, aboveSubview: self.view)
    }
    
    func getUsers () {
        Task {
            let (res,error) = await ghttpService.requestNearUsers(tel)
            
            await MainActor.run {
                if error == nil{
                    var users = [DMCCUser]()
                    res?.forEach({ osnid in
                        let user = gosnUser.getUserInfoDefault(osnid)
                        users.append(user)
                    })
                    userArray = users
                    self.tableView.reloadData()
                    if userArray.count > 0 {
                        self.nullView.removeFromSuperview()
                    }
                    if listApi.count > 0 {
                        getDapps()
                    }else{
                        if self.userArray.count == 0{
                            self.view .insertSubview(self.nullView, aboveSubview: self.view)
                        }
                    }
                }
            }
        }
         
    }
    
    func getDapps () {
        // 创建URL对象
        let url = "\(listApi)?current=1&size=1000&tel=\(tel)"
        if let url = URL(string: url) {
            // 创建URLSessionDataTask
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                // 确保没有错误发生
                if let error = error {
                    print("Error: \(error)")
                    return
                }
                
                // 确保我们得到了数据
                guard let data = data else {
                    print("未收到数据")
                    return
                }
                
                // 尝试解析数据
                do {
                    // 假设数据是JSON格式
                    if let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
                        
                        if let data = dict["data"] as? [String:Any]{
                            if let page = data["page"] as? [String:Any]{
                                if let records = page["records"] as? [NSDictionary]{
                                    records.forEach { dic in
                                        let dapp = DMCCDapp.deserialize(from: dic)
                                        self.dataSource.append(dapp as Any)
                                    }
                                }
                            }
                        }
                    }
                    
                    GK_main_async_safe {
                        if self.dataSource.count == 0 && self.userArray.count == 0{
                            self.view .insertSubview(self.nullView, aboveSubview: self.view)
                        }else {
                            self.nullView.removeFromSuperview()
                        }
                        self.tableView.reloadData()
                    }
                } catch {
                    print("解析错误: \(error)")
                }
            }
            
            // 启动任务
            task.resume()
        }
    }
    

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if indexPath.section == 0 {
//            return 44
            if more.url.count > 0 {
                return 44
            }else {
                return 0.001
            }
        }
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
//            return 1
            if more.url.count > 0 && dataSource.count > 0{
//            if more.url.count > 0 {
                return 1
            }else {
                return 0
            }
        }
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            if userArray.count == 0 {
                return 0.001
            }
            if userArray.count <= 5 {
                return 110
            }
            return 200
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {
            let head = tableView.dequeueReusableHeaderFooterView(withIdentifier: "NearHeadView") as! NearHeadView
            head.delegate = self

            head.data = self.userArray

            head.update()
            return head
        }
        return UIView()
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "NearMoreCell", for: indexPath) as! NearMoreCell
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
            let dapp = self.dataSource[indexPath.row]
            cell.setDapp(dapp: dapp as! DMCCDapp)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 0 {
            if more.url.count > 0 && dataSource.count > 0{
//            if more.url.count > 0{
                self.presentVC(VC: YLNavigationVC(rootViewController: WebVC(appInfo: more, dismissCompletion: {
                  
                                                })))
            }
        }else {
            let info = dataSource[indexPath.row] as? DMCCDapp
            if info!.dappInfo.count > 0 {
                let dappInfo = gosnDapp.fromJson(info!.dappInfo.toJson()!)
                self.presentVC(VC: YLNavigationVC(rootViewController: WebVC(appInfo: dappInfo, dismissCompletion: {
                  
                                                })))
            }
        }

    }
    
    
    func FriendSeeBlock(index: Int) {
        let userInfo = userArray[index]

        if userInfo.userId == gosnUser.myId() {
            self.navigationController?.pushViewController(MySetVC(), animated: true)
        }else if gosnFriend.isFriend(userInfo.userId) {
            let detailViewController = UserDetailVC(userInfo: userInfo)
            navigationController?.pushViewController(detailViewController, animated: true)
        } else {
            let addFriendViewController = AddUserVC(userInfo: userInfo)
            navigationController?.pushViewController(addFriendViewController, animated: true)
        }

    }
    
    func FriendAddBlock() {
        
    }
    
    func FriendLessBlock() {
        
    }
    
    func FriendSeeMoreBlock() {
        
    }

}
